package com.heima.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.heima.utils.common.MD5Utils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.判断是否包含用户信息
        if (StrUtil.isNotBlank(dto.getPhone()) && StrUtil.isNotBlank(dto.getPassword())) {
            //1.1根据手机号查询用户信息
            ApUser one = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (ObjectUtil.isEmpty(one)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在,请注册");
            }

            String hashpd = one.getPassword();
            String password = dto.getPassword();
            boolean checkpw = BCrypt.checkpw(password, hashpd);
            if (!checkpw){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户密码,请重新输入");
            }
            //1.3返回数据 jwt user
            String token = AppJwtUtil.getToken(one.getId().longValue());
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            one.setPhone("");
            one.setPassword("");
            map.put("user",one);
            return ResponseResult.okResult(map);
        }else {
            Map<String,Object> map = new HashMap<>();
            String token = AppJwtUtil.getToken(0L);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
